using System;
using System.Data;
using System.IO;
using System.Xml;
using System.Runtime.Serialization;

namespace FreeFlow.Administration
{
	/// <summary>
	/// A script used to authenticate users.
	/// </summary>
  public class AuthenticationScript : DatabaseAware, IUpdatable, IDeletable
  {
    private AuthenticationScriptCollection owner;
    internal AuthenticationScript(Server server, AuthenticationScriptCollection owner, XmlNode xml) : base(server)
    {
      // get the script
      byte[] scriptBytes = Server.GetAttachment(AttachmentType.Service, xml.Attributes["Name"].Value, "oa");
      LoadScript(owner, xml.Attributes["Name"].Value, scriptBytes);
    }

    internal AuthenticationScript(Server server, AuthenticationScriptCollection owner, 
      string name, byte[] data) : base(server)
    {
      LoadScript(owner, name, data);
    }

    private void LoadScript(AuthenticationScriptCollection owner, string name, byte[] data)
    {
      this.owner = owner;
      this.name = name;

      if (data != null)
      {
        script = Attachment.ByteArrayToString(data);
      }
    }

    /// <summary>
    /// Gets a value indicating whether this script is the script used for guest access.
    /// </summary>
    /// <value>
    /// 	<c>true</c> if this script is the script used for guest access; otherwise, <c>false</c>.
    /// </value>
    public bool IsGuestScript
    {
      get
      {
        return (owner.GuestUserScript == this);
      }
    }

    private string name;
    /// <summary>
    /// Gets the name of the script.
    /// </summary>
    public string Name
    {
      get
      {
        return name;
      }
    }

    private string script;
    /// <summary>
    /// Gets or sets the script contents.
    /// </summary>
    public string Script
    {
      get
      {
        return script;
      }
      set
      {
        script = value;
      }
    }

    #region IUpdatable Members

    /// <summary>
    /// Applies the changes made to this script.
    /// </summary>
    public void ApplyChanges()
    {
      // get the bytes
      using (MemoryStream stream = new MemoryStream())
      using (StreamWriter writer = new StreamWriter(stream))  
      {
        writer.Write(script);
        writer.Flush();
        byte[] scriptBytes = stream.ToArray();

        Server.SetAttachment(AttachmentType.Service, name, "oa", scriptBytes);
      }
    }

    #endregion
    #region IDeletable Members

    /// <summary>
    /// Deletes this authentication script.
    /// </summary>
    public void Delete()
    {
      // delete from database
      Server.DeleteAttachment(AttachmentType.Service, name, "oa");

      // inform owner collection to remove this script
      owner.Remove(this);
    }

    #endregion
  }
}
